import {
  postLogin,
  getCode
} from '../../api/login'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile: "",
    code: '',
    getCode: ''
  },
  checkPhone(mobile) {
    let RegExp = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    return RegExp.test(mobile)
  },
  login() {
    let that = this
    let {
      code,
      mobile,
      getCode
    } = this.data

    if (!mobile) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
      })
      return
    }
    if (!this.checkPhone(mobile)) {
      wx.showToast({
        title: '手机号格式有误',
        icon: 'none',
      })
      return
    }

    if (!getCode) {
      wx.showToast({
        title: '请获取验证码',
        icon: 'none',
      })
      return
    }
    if (!code) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
      })
      return
    }
    if (code !== getCode) {
      wx.showToast({
        title: '验证码错误',
        icon: 'none',
      })
      return
    }

    const login = async function () {
      let res = await postLogin({
        mobile: that.data.mobile,
        code: that.data.code
      })

      if (res.data.code === 10000) {
        wx.showToast({
          title: '登录成功',
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000);

        wx.setStorage({
          key: 'token',
          data: res.data.data.token
        })
        wx.setStorage({
          key: 'refreshToken',
          data: res.data.data.refreshToken
        })

      }

    }
    login()
  },
  getCodeFn() {
    let {
      mobile
    } = this.data
    if (!mobile) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
      })
      return
    }
    if (!this.checkPhone(mobile)) {
      wx.showToast({
        title: '手机号格式有误',
        icon: 'none',
      })
      return
    }
    let that = this
    const getCodeFn = async function () {
      let res = await getCode({
        mobile: that.data.mobile
      })
      if (res.data.code === 10000) {
        wx.showToast({
          title: '验证码：' + res.data.data.code,
          duration: 3000
        })
        that.setData({
          getCode: res.data.data.code
        })
      }
    }
    getCodeFn()
  }
})